package com.syeet.gulimall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syeet.common.to.mq.StockDetailTo;
import com.syeet.common.to.mq.StockLockedTo;
import com.syeet.common.utils.PageUtils;
import com.syeet.common.utils.Query;
import com.syeet.common.utils.R;
import com.syeet.gulimall.ware.dao.WareSkuDao;
import com.syeet.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.syeet.gulimall.ware.entity.WareOrderTaskEntity;
import com.syeet.gulimall.ware.entity.WareSkuEntity;
import com.syeet.gulimall.ware.exception.NoStockException;
import com.syeet.gulimall.ware.feign.ProductFeignService;
import com.syeet.gulimall.ware.service.WareOrderTaskDetailService;
import com.syeet.gulimall.ware.service.WareOrderTaskService;
import com.syeet.gulimall.ware.service.WareSkuService;
import com.syeet.gulimall.ware.vo.OrderItemVo;
import com.syeet.gulimall.ware.vo.SkuHasStockVo;
import com.syeet.gulimall.ware.vo.WareSkuLockVo;
import lombok.Data;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RabbitListener(queues = "stock.release.stock.queue")
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired(required = false)
    private WareSkuDao wareSkuDao;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    private WareOrderTaskService wareOrderTaskService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         * skuId: 1
         * wareId: 1
         */
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            queryWrapper.eq("sku_id", skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            queryWrapper.eq("ware_id", wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //判断没有库存记录则为新增操作
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>()
                .eq("sku_id", skuId).eq("ware_id", wareId));
        if (CollectionUtils.isEmpty(wareSkuEntities)) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            //TODO 远程查询sku_name 如果失败，事务无需回滚
            try {
                R info = productFeignService.info(skuId);
                Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
                if (info.getCode() == 0) {
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {

            }
            wareSkuDao.insert(wareSkuEntity);
        } else {
            //有记录添加
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }

    }

    /**
     * 查询所有当前skuId剩余的库存量
     *
     * @param skuIds
     * @return
     */
    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {

        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            //查询当前中库存量
            //select sum(stock-stock_locked) from wms_ware_sku where sku_id =1
            Long count = this.baseMapper.selectCountStock(skuId);
            skuHasStockVo.setSkuId(skuId);
            skuHasStockVo.setHasStock(count == null ? false : count > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());

        return collect;
    }

    /**
     * 1.为某个订单锁定库存
     * <p>
     * 2.库存解锁场景
     * 1）订单过期没有支付被自动取消，或者用户自己取消
     * 2）下订单成功，库存锁定成功，但是接下来业务调用失败，
     * 导致订单回滚，之前锁定的库存也要自动解锁（不用seata做分布式事务回滚，是at模式因为不适用高并发）
     *
     * @param vo
     * @return
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        //保存库存工作单的详情，用于追溯
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(wareOrderTaskEntity);

        //按照下单的收货地址，找到一个就近仓库，锁定库存
        //1.找到每一个商品在哪个仓库有库存
        List<OrderItemVo> orderItemVos = vo.getLocks();
        List<SkuWareHasStock> skuWareHasStockList = orderItemVos.stream().map(orderItemVo -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = orderItemVo.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(orderItemVo.getCount());
            //查找这个商品在哪些仓库有库存，找出仓库id
            List<Long> wareIds = wareSkuDao.listWareIdHasStock(skuId);
            stock.setWareIds(wareIds);
            return stock;
        }).collect(Collectors.toList());

        //2.锁定库存
        for (SkuWareHasStock stock : skuWareHasStockList) {
            Boolean skuLockFlag = false;
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareIds();
            if (CollectionUtils.isEmpty(wareIds)) {
                throw new NoStockException(skuId);
            }
            //1、如果每一个商品都锁定成功,将当前商品锁定了几件的工作单记录发给MQ
            //2、锁定失败（哪怕一个失败都是失败）。前面保存的工作单信息都回滚了。发送出去的消息，
            // 即使要解锁库存，由于在数据库查不到指定的id，所有就不用解锁
            for (Long wareId : wareIds) {
                //成功返回影响行数1，否则为0
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, stock.getNum());
                if (count == 1) {
                    skuLockFlag = true;
                    WareOrderTaskDetailEntity taskDetailEntity = WareOrderTaskDetailEntity.builder()
                            .skuId(skuId)
                            .skuName("")
                            .skuNum(stock.getNum())
                            .taskId(wareOrderTaskEntity.getId())
                            .wareId(wareId)
                            .lockStatus(1)
                            .build();
                    wareOrderTaskDetailService.save(taskDetailEntity);

                    //TODO 告诉MQ库存锁定成功
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(wareOrderTaskEntity.getId());
                    StockDetailTo detailTo = new StockDetailTo();
                    BeanUtils.copyProperties(taskDetailEntity,detailTo);
                    lockedTo.setDetailTo(detailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",lockedTo);
                    break;
                } else {
                    //当前仓库锁库存失败，重试下一个仓库
                }
            }
            if (!skuLockFlag) {
                //当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }

        return true;
    }

    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareIds;
    }
}